﻿from PIL import Image, ImageDraw, ImageFont

def create_text_watermark(text="Watermark", 
                         font_size=40, 
                         opacity=0.5, 
                         font_path=None,
                         output_path="watermark.png"):
    """
    生成500x500透明背景的文字水印，文字在四角对称分布
    
    参数:
    text: 水印文字内容
    font_size: 字体大小
    opacity: 透明度 (0~1)
    font_path: 自定义字体路径（None为系统默认字体）
    output_path: 输出图片路径
    """
    # 校验透明度
    opacity = max(0, min(1, opacity))
    
    # 加载字体
    try:
        if font_path:
            font = ImageFont.truetype(font_path, font_size)
        else:
            font = ImageFont.load_default().font_variant(size=font_size)
    except Exception as e:
        raise ValueError(f"字体加载失败: {e}")

    # 固定画布尺寸为500x500
    image_size = (500, 500)
    image = Image.new("RGBA", image_size, (255, 255, 255, 0))
    draw = ImageDraw.Draw(image)
    
    # 计算文本实际边界框
    bbox = draw.textbbox((0, 0), text, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]
    
    # 定义四角坐标 (左上、右上、左下、右下)
    positions = [
        (10 - bbox[0], 10 - bbox[1]),  # 左上
        (490 - bbox[2], 10 - bbox[1]),  # 右上 (500-10-text_width)
        (10 - bbox[0], 490 - bbox[3]),  # 左下 (500-10-text_height)
        (490 - bbox[2], 490 - bbox[3])  # 右下
    ]
    
    # 在所有对称位置绘制文字
    for x, y in positions:
        draw.text((x, y), 
                 text, 
                 font=font, 
                 fill=(255, 255, 255, int(255 * opacity)))
    
    # 保存水印
    image.save(output_path, "PNG")

# 使用示例
if __name__ == "__main__":
    create_text_watermark(
        text="LXRLXR",
        font_size=190,
        opacity=0.6,
        font_path=None,  # 可选
        output_path="symmetrical_watermark.png"
    )